class Dep {
    constructor() {
        this.subscribers = new Set();
    }
    depend() {
        if (activeEffect) {
            this.subscribers.add(activeEffect);
        }
    }
    notify() {
        this.subscribers.forEach((fn) => {
            fn()
        })
    }
}

let activeEffect = null
const watchEffect = function (effect) {
    activeEffect = effect
    effect()
    activeEffect = null
}

/* 
weakMap可以支持 对象作为key 弱引用 
 Map 字符串作为key
*/
let targetMap = new WeakMap()
function getDep(target, key) {
    let map = targetMap.get(target);
    if (!map) {
        map = new Map()
        targetMap.set(target, map)
    }

    let depend = map.get(key)
    if (!depend) {
        depend = new Dep()
        map.set(key, depend)
    }
    return depend
}


function reactive(raw) {
    return new Proxy(raw, {
        get(target, key, receiver) {
            const depend = getDep(target, key)
            depend.depend()
            return Reflect.get(target, key, receiver)
        },
        set(target, key, newValue, receiver) {
            Reflect.set(target, key, newValue, receiver)
            const depend = getDep(target, key);
            depend.notify()
        }
    })

}
